package busuanzi;

import busuanzi.module.*;
import io.netty.handler.codec.http.HttpHeaderNames;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

import static com.google.common.base.Strings.isNullOrEmpty;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static sardine.Sardine.*;

/**
 * 不蒜子
 * <p/>
 * Auth: bruce-sha
 * Date: 2015/4/14
 */
public class BootMain {

    public static void main(String[] args) {

        /****************************** 配置等 ******************************/

        port(9527);

        staticFileLocation(""); // 相对于classpath 的 Static files（可以是jar也可以是非jar）
        // externalStaticFileLocation("/var/angularjs/"); // 操作系统的 Static files

        /****************************** 前置过滤器 ******************************/

//        before("/counter", (request, response) -> {
////            String sessionId = request.cookie("busuanziId");
////            if (sessionId == null)
////                response.cookie("busuanziId", UUID.randomUUID().toString(), Long.MIN_VALUE);
//        });

//        before("/", (request, response) -> {
//            // 可不可以做到只能在before中rewirte
//            request.rewrite("/index.html");
//        });

        before("/", (request, response) -> {
            request.rewrite("/index.html");// 可不可以做到只能在before中rewirte
        });

        Services.run();
        Securities.run();
        Statistics.run();
        Administrations.run();
        Backs.run();

        /****************************** 主页 ******************************/

//        get("/", (request, response) -> {
//            response.redirect("/index.html");
//            return HttpResponseStatus.OK;
//        });

        /****************************** security ******************************/


        /****************************** restful 1.0 ******************************/
        get("/etag", (request, response) -> {
            String etag = request.headers(HttpHeaderNames.ETAG);
            if (isNullOrEmpty(etag))
                response.header(HttpHeaderNames.ETAG, "123");

            return "hello hello hello" + System.currentTimeMillis() + " hello hello hello";
        });

        get("/busuanzi/2.0/sites", (request, response) -> {
            return "hello hello hello" + System.currentTimeMillis() + " hello hello hello";
        });


        get("/hi/:name", (request, response) -> {
            return "hi" + request.params(":name") + System.currentTimeMillis();
        });

        // matches "GET /say/hello/to/world"
        // request.splat()[0] is 'hello' and request.splat()[1] 'world'
        get("/say/*/to/*", (request, response) -> {
            return "Number of splat parameters: " + request.splats().length;
        });

        get("/hello", (request, response) -> {
            return "哇咔咔";
        });

        get("/hello4", (request, response) -> {
            halt(405, "wacaca");
            return "hello" + System.currentTimeMillis();
        });


        /****************************** 后置过滤器 ******************************/


        /****************************** 统计 ******************************/


        /****************************** 自定义404 ******************************/

        notFound("<html><body><h2>404 Not found</h2><p>i got you !</p></body></html>");


        /****************************** 玩 ******************************/

//        //http://service.ibruce.info/fake?_pv=20000&_uv=1000&_pg=10000
//        get("/fake", (request, response) -> {
//            return MongoClient.bath("busuanzi/busuan", collection -> {
//
//                int pv = Integer.valueOf(request.queryParams("_pv"));
//                int uv = Integer.valueOf(request.queryParams("_uv"));
//                int pg = Integer.valueOf(request.queryParams("_pg"));
//
//                Document siteUVDoc = collection.findOneAndUpdate(
//                        newDocument("host", "service.ibruce.info", "path", "_uv"),
//                        newDocument("$inc", newDocument("count", uv)));
//
//                // { "_id" : ObjectId("553868be45fa47d335c21ed4"),
//                //   "host" : "localhost", "path" : "_pv", "count" : 9 }
//                Document sitePVDoc = collection.findOneAndUpdate(
//                        newDocument("host", "service.ibruce.info", "path", "_pv"),
//                        newDocument("$inc", newDocument("count", pv)));
//
//                // { "_id" : ObjectId("553868be45fa47d335c21ed6"),
//                //   "host" : "localhost", "path" : "/test/test.html", "count" : 9 }
//                Document pagePVDoc = collection.findOneAndUpdate(
//                        newDocument("host", "service.ibruce.info", "path", "/"),
//                        newDocument("$inc", newDocument("count", pg)));
//
//                return "ok";
//            });
//        }, Sugar.HtmlJsonTransformer);

        // ab -n 10000 -c 100 -k  localhost:9527/hunt
        // apr_poll: The timeout specified has expired (70007) 原因是1.0的request 1.1的response
        get("/hunt", (request, response) -> {
            // response.header(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
            response.header(CONNECTION, KEEP_ALIVE);

            return System.currentTimeMillis() + "<br>" + request;
        });

        get("/now", (request, response) -> {

            LocalDateTime totalBegin = LocalDateTime.of(2014, 11, 4, 0, 0, 0, 0);
            long totalDays = ChronoUnit.DAYS.between(totalBegin, LocalDateTime.now());
            Period p = Period.between(totalBegin.toLocalDate(), LocalDate.now());

            // LocalDateTime floorBegin = LocalDateTime.of(2015, 2, 4, 0, 0, 0, 0);
            // long floorDays = ChronoUnit.DAYS.between(floorBegin, LocalDateTime.now());
            // Period p2 = Period.between(floorBegin.toLocalDate(), LocalDate.now());

            return String.format("<p> now at %s </p> <p>total days %s period %s </p>",
                    System.currentTimeMillis(), totalDays, p);
        });
    }
}
